package com.yanqu.road.dao.impl.wingroom;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.wingroom.workshop.WorkShopItem;
import com.yanqu.road.entity.wingroom.workshop.WorkShopPool;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：zfr
 * @date ：2022/3/22 18:18
 */
public class WorkShopPoolDaoImpl extends TempDao {

    public static String insertSql = "REPLACE INTO t_c_workshop_pool(refreshTime,workShopItemList) values(?,?)";
    public boolean addData(WorkShopPool data) {
        getDb().setConnName(DbNameStrategy.getCrossDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.BIGINT, data.getRefreshTime()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSONObject.toJSONString(data.getWorkShopItemList())));
        if (getDb().executeNoneQuery(insertSql, para) > 0) {
            return true;
        }
        return false;
    }

    protected WorkShopPool parseData(ResultSet rs) throws SQLException {
        WorkShopPool data = new WorkShopPool();
        data.setRefreshTime(rs.getLong("refreshTime"));
        data.setWorkShopItemList(JSONObject.parseObject(rs.getString("workShopItemList"), new TypeReference<List<WorkShopItem>>() {
        }));
        return data;
    }

    public WorkShopPool getWorkShopPool(long refreshTime) {
        ResultSet rs = null;
        CallableStatement call = null;
        WorkShopPool data = null;
        String sql = "select * from t_c_workshop_pool where refreshTime = ?";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, refreshTime);
            rs = call.executeQuery();
            while (rs.next()) {
                data = parseData(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return data;
    }
}
